package com.cskaoyan.bytestream;

import java.io.*;

/*

        文件复制
        把d:\\a.txt内容复制到e:\\b.txt中
        把e:\\**.jpg内容复制到当前项目目录下的mn.jpg
 */
public class Exercise {

    public static void main(String[] args) throws IOException {

        String srcPath = "d:\\one\\a.txt";
        String destPath = "d:\\another\\b.txt";
        // 复制文本文件
        copyTxtFile(srcPath, destPath);


        // 复制图片文件
        String src = "d:\\demo\\picture.jpg";
        String dest = "d:\\picture.jpg";
        //copyPictureFile(src, dest);


    }

    public static void copyTxtFile(String srcPath, String destPath) {
        InputStream fis = null;
        OutputStream fos = null;
        try {
            // 1. 创建流对象
            fis = new FileInputStream(srcPath);
            fos = new FileOutputStream(destPath);


            // 2. 读源文件中的数据
            int readByte;
            // 循环从源文件中读取数据，并写入目标文件
            while ((readByte = fis.read()) != -1) {
                // 将读取到的字节数组中的数据，写入目标文件
                fos.write(readByte);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            closeQuietly(fis);
            closeQuietly(fos);
        }
    }

    public static void closeQuietly(Closeable closeable) {
        try {
            closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyPictureFile(String srcPath, String destPath) throws IOException {

        // 创建流对象
       OutputStream fos = new FileOutputStream(destPath);
       InputStream fis = new FileInputStream(srcPath);


        int count;
        byte[] bytes = new byte[1024];
        // 读取源文件数据，写入目标文件
        while ((count = fis.read(bytes)) != -1) {
            // 写入读取到的数据
            fos.write(bytes, 0, count);
        }

        // 关闭流
        fos.close();
        fis.close();

    }



}
